package cn.itcast.nems.common.web.interceptor;

import cn.itcast.nems.common.tenant.TenantInfo;
import cn.itcast.nems.common.tenant.TenantInfoHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;


@Slf4j
@Component
public class TenantInfoInterceptor implements HandlerInterceptor {
    private static final String TENANT_ID = "tenantId";
    private static final String SUBTENANT_ID = "subtenantId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String tenantIdHeader = request.getHeader(TENANT_ID);
        String subtenantIdHeader = request.getHeader(SUBTENANT_ID);
        if (StringUtils.hasText(tenantIdHeader)) { // oapi网关转发的请求
            // 注：租户和子租户值是前端传入，此处必须使用integer的值，否则会导致SQL注入漏洞。
            int tenantId = Integer.parseInt(tenantIdHeader.trim());
            int subtenantId = Integer.parseInt(subtenantIdHeader.trim());
            TenantInfoHolder.setTenantInfo(new TenantInfo(tenantId, subtenantId));
        } else {// 前端UI调用
            TenantInfoHolder.setTenantInfo(new TenantInfo(TenantInfo.DEFAULT_TENANT_ID, TenantInfo.DEFAULT_SUBTENANT_ID));
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        TenantInfoHolder.clear();
    }
}
